package cn.leonis.leetcode;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * @Author Tobi
 * @Date 2022-05-27 下午1:53
 * leetcode 961 从2N长度的数组中查找N长度的元素
 */
public class FindNRepeatIn2NArraySolution {
    public static void main(String[] args) {
        int[] nums = {1, 3, 2, 3, 4, 3};
        FindNRepeatIn2NArraySolution solution = new FindNRepeatIn2NArraySolution();
        System.out.println(solution.repeatedTimes(nums));
        System.out.println(solution.repeatedTimes1(nums));
        System.out.println(solution.repeatedTimes2(nums));
    }

    /**
     * 解法一，先排序，那么中间的那个元素如果和旁边的相同，就一定是要查找的元素
     * @param nums
     * @return
     */
    public int repeatedTimes(int[] nums) {
        Arrays.sort(nums);
        int mid = nums.length / 2;
        return nums[mid] == nums[mid + 1] ? nums[mid] : nums[mid - 1];
    }

    /**
     * 解法二：随机选择法
     * @param nums
     * @return
     */
    public int repeatedTimes1(int[] nums) {
        int n = nums.length;
        Random random = new Random();

        while (true) {
            int x = random.nextInt(n), y = random.nextInt(n);
            if (x != y && nums[x] == nums[y]) {
                return nums[x];
            }
        }
    }

    /**
     * 解法三：摩尔投票法，对抗抵消
     * @param nums
     * @return
     */
    public int repeatedTimes2(int[] nums) {
        int n = nums.length;
        int start = nums[0];
        int cand = nums[0];
        for (int i = 1; i < n; i++) {
            if (nums[i] == start) {
                return start;
            }
            if (nums[i] == cand) {
                return cand;
            }
            cand = nums[i];
        }
        return cand;
    }

    /**
     * 解法四：哈希表法
     * @param nums
     * @return
     */
    public int repeatedTimes3(int[] nums) {
        Set<Integer> ints = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (!ints.add(nums[i])) {
                return nums[i];
            }
        }
        return -1;
    }
}
